class Nes {
    constructor(game) {
        this.game = game 
        this.data = mariosData
        this.setUp()
    }
    setUp() {
        this.context = this.game.context
        this.offset = 36880 
        this.pixelSize = 8
        this.pixelWidth = 2
        this.numberOfBytesPerBlock = 16
        // 0 的起始位置
        let offset = this.offset
        this.data = this.data.slice(offset)

        this.number = 0
        this.x = 130
        this.y = 50
    }
    drawNumber() {
        let number = this.number
        let numbers = splited_number(number)
        let width = numbers.length * this.pixelWidth * this.pixelSize
        let offsetX = this.x - (Math.floor(width / 2))
        let y = this.y
        for (let i = 0; i < numbers.length; i++) {
            let x = offsetX + i * this.pixelWidth * this.pixelSize
            this.drawOneNumber(numbers[i], x, y)
        }
    }


    drawOneNumber(number, x, y) {
        let index = number * this.numberOfBytesPerBlock
        var data = this.data.slice(index)
        this.drawBlock(data, x, y)
    }
    drawBlock(data, x, y){
        const colors = [
            'white',
            '#D91F03', 
            '#F79232',
            '#816A00',
        ]
        let w = this.pixelWidth
        let h = this.pixelWidth
        let blockSize = 8
        for (let i = 0; i < blockSize; i++) {
            let p1 = data[i]
            let p2 = data[i + 8]
            for (let j = 0; j < blockSize; j++) {
                let c1 = (p1 >> (7 - j)) & 0b00000001
                let c2 = (p2 >> (7 - j)) & 0b00000001
                let pixel = (c2 << 1) + c1
                let color = colors[pixel]
                if (color == "white") {
                    continue
                }
                this.context.fillStyle = color
                let px = x + j * w
                let py = y + i * h
                this.context.fillRect(px, py, w, h)
            }
            
        }
    }

    update() {
    }
    draw() {
        this.drawNumber()
    }
}

const numberPosCount = (number) => {
    let count = 1
    let n = number
    while (n >= 10) {
        n = Math.floor(n / 10)
        count += 1
    }
    return count
}

const splited_number = (number) => {
    let count = numberPosCount(number)
    let results = []
    for (let i = count - 1; i >= 0; i--) {
        let n = Math.floor(number / Math.pow(10, i))
        number -= Math.pow(10, i) * n
        results.push(n)
    }
    return results
}